package com.dayfly.tip.action;

import java.util.List;
import java.util.Map;

import weibo4j.UserInfo;
import weibo4j.Weibo;
import weibo4j.examples.WebOAuth;
import weibo4j.http.AccessToken;
import weibo4j.http.RequestToken;

import com.dayfly.tip.dao.WeiboDAO;
import com.dayfly.tip.model.WeiboToken;
import com.dayfly.tip.model.consts.WeiboType;
import com.opensymphony.xwork2.ActionContext;

/**
 * 
 * @author zhaopingfei
 * 
 *         2011-6-2
 */
public class SinaWeibo extends BaseAction {

	private static final long serialVersionUID = -7990858568718165025L;

	public static final String appkey = "197240715";

	public static final String appSecret = "dd00157c190d342f4770559f7cb77d46";

	private WeiboDAO weiboDAO;

	public void setWeiboDAO(WeiboDAO weiboDAO) {
		this.weiboDAO = weiboDAO;
	}

	public String execute() throws Exception {
		ActionContext tx = ActionContext.getContext();
		Long userId = (Long) tx.getSession().get("userId");
		if (userId == null) {
			return LOGIN;
		} else {
			WeiboToken token = getTokenByUserId(userId,WeiboType.SINA.getValue());
			// 若系统里没有保存号的token，则证明此人需要授权才能使用此功能
			if (token == null) {
				RequestToken resToken = WebOAuth
						.request("http://localhost:8080/tip/new/weiboverify.action");
				tx.getContextMap().put("url", resToken.getAuthenticationURL());
				tx.getSession().put("token", resToken);
				return "revoke";
			}
		}
		return "publish";
	}

	private WeiboToken getTokenByUserId(long userId,int type) {
		return weiboDAO.getWeiboTokenByUserId(userId,type);
	}

	/**
	 * 将token和用户的对应关系保存到数据库
	 * 
	 * @param userId
	 * @param accessToken
	 */
	private void saveToken(Long userId, AccessToken accessToken) {
		WeiboToken token = new WeiboToken();
		token.setAccessKey(accessToken.getToken());
		token.setAccessSecret(accessToken.getTokenSecret());
		token.setUserId(userId);
		token.setUid(accessToken.getUserId());
		token.setType(WeiboType.SINA.getValue());
		weiboDAO.saveWeiboToken(token);
	}

	/**
	 * 
	 * 保存用户的授权token
	 * 
	 * @return
	 * @throws Exception
	 */
	public String verify() throws Exception {
		ActionContext tx = ActionContext.getContext();
		Map<String, Object> session = tx.getSession();
		long userId = (Long) tx.getSession().get("userId");
		RequestToken token = (RequestToken) session.get("token");
		String[] verifier = (String[]) tx.getParameters().get("oauth_verifier");
		if (token == null || verifier == null) {
			return ERROR;
		}
		AccessToken accessToken = WebOAuth
				.requstAccessToken(token, verifier[0]);
		session.put("accessToken", accessToken);
		saveToken(userId, accessToken);
		return SUCCESS;
	}

	/**
	 * 发布一条微博
	 * 
	 * @return
	 * @throws Exception
	 */
	public String publishWeibo() throws Exception {
		ActionContext tx = ActionContext.getContext();
		String[] content = (String[]) tx.getParameters().get("content");
		if (content == null) {
			return INPUT;
		}
		AccessToken accToken = (AccessToken) tx.getSession().get("accessToken");
		long userId = (Long) tx.getSession().get("userId");
		if (accToken == null) {
			accToken = getDbToken(userId, WeiboType.SINA.getValue());
		}
		WebOAuth.update(accToken, content[0]);
		return INPUT;

	}

	/**
	 * 关注我
	 * 
	 * @return
	 * @throws Exception
	 */
	public String attentionMe() throws Exception {
		Weibo weibo = new Weibo();
		ActionContext tx = ActionContext.getContext();
		AccessToken accToken = (AccessToken) tx.getSession().get("accessToken");
		long userId = (Long) tx.getSession().get("userId");
		if (accToken == null) {
			accToken = getDbToken(userId, WeiboType.SINA.getValue());
			if (accToken == null) {
				return "verify";
			}
		}
		weibo.setToken(accToken.getToken(), accToken.getTokenSecret());
		weibo.createFriendship("1826224505");
		return INPUT;
	}

	private AccessToken getDbToken(long userId, int value) {
		WeiboToken dbToken = getTokenByUserId(userId, WeiboType.SINA.getValue());
		if(dbToken == null){
			return null;
		}
		AccessToken token = new AccessToken(dbToken.getAccessKey(), dbToken.getAccessSecret());
		token.setUserId(dbToken.getUid());
		String[] mockResponse ={"oauth_token="+token.getToken(), "oauth_token_secret="+token.getTokenSecret(), "user_id="+token.getUserId()};
		token.setResponseStr(mockResponse);
		return token;
	}

	public String getSuggest() throws Exception {
		ActionContext tx = ActionContext.getContext();
		String[] input = (String[]) tx.getParameters().get("input");
		Weibo weibo = new Weibo();
		AccessToken accToken = (AccessToken) tx.getSession().get("accessToken");
		long userId = (Long) tx.getSession().get("userId");
		if (accToken == null) {
			accToken = getDbToken(userId, WeiboType.SINA.getValue());
			if (accToken == null) {
				return "verify";
			}
		}
		weibo.setToken(accToken.getToken(), accToken.getTokenSecret());
		List<UserInfo> users = weibo.getUserSuggestions(input[0]);
		tx.getContextMap().put("userInfo", users);
		return INPUT;
	}

}
